package com.qupai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qupai.dto.GoodsSalesDTO;
import com.qupai.entity.Orders;
import com.qupai.entity.User;
import com.qupai.mapper.OrderMapper;
import com.qupai.mapper.UserMapper;
import com.qupai.service.ReportService;
import com.qupai.vo.OrderReportVO;
import com.qupai.vo.SalesTop10ReportVO;
import com.qupai.vo.TurnoverReportVO;
import com.qupai.vo.UserReportVO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ReportServiceImpl implements ReportService {

    private final OrderMapper orderMapper;
    private final UserMapper userMapper;

    /**
     * 统计指定时间区间内的营业额数据
     * @param begin 开始时间
     * @param end 结束时间
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {

        //turnoverReportVO里面日期对象操作,是表的横轴
        //当前集合用于存放从begin到end范围内的每天日期
        List<LocalDate> dateList=new ArrayList<>();

        dateList.add(begin);
        while (!begin.equals(end)){
            //日期计算，计算指定日期的后一天对应的日期
            begin=begin.plusDays(1);
            dateList.add(begin);
        }

        //org.apache.commons.lang3.StringUtils工具包里面方法封装对应TurnoverReportVO里面要求的前端数据格式
        String joinDateList = StringUtils.join(dateList, ",");

        //turnoverReportVO里面营业额对象操作，是表的纵轴
        //存放每天营业额
        List<Double> turnoverList=new ArrayList<>();
        for (LocalDate date : dateList) {
            //查询data日期对应的营业额数据,营业额是指：状态为“已完成==>Orders对象里面为4”的订单金额合计
            LocalDateTime beginTime=LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime=LocalDateTime.of(date, LocalTime.MAX);

            Map<String, Object> map=new HashMap<>();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);

            turnover=(turnover==null)?0.0:turnover;
            turnoverList.add(turnover);
        }
        String joinTurnoverList = StringUtils.join(turnoverList, ",");

        //封装返回结果turnoverReportVO

        return TurnoverReportVO.builder()
                .dateList(joinDateList)
                .turnoverList(joinTurnoverList)
                .build();
    }

    /**
     * 统计指定时间区间内的用户数据
     * @param begin 开始时间
     * @param end 结束时间
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //当前集合用于存放从begin到end范围内的每天日期
        List<LocalDate> dateList=new ArrayList<>();

        dateList.add(begin);
        while (!begin.equals(end)){
            //日期计算，计算指定日期的后一天对应的日期
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        //org.apache.commons.lang3.StringUtils工具包里面方法封装对应UserReportVO里面要求的前端数据格式
        String joinDateList = StringUtils.join(dateList, ",");

        //存放每天用户新增数量
        List<Long> newUserList = new ArrayList<>();
        //存放每天用户总量
        List<Long> totalUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //查询data日期对应的用户数量
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            QueryWrapper<User> queryWrapper=new QueryWrapper<>();
            queryWrapper.lambda().le(endTime!=null,User::getCreateTime,endTime);
            Long totalUser=userMapper.selectCount(queryWrapper);
            queryWrapper.lambda().ge(beginTime!=null,User::getCreateTime,beginTime);
            Long newUser=userMapper.selectCount(queryWrapper);

            totalUserList.add(totalUser);
            newUserList.add(newUser);
        }

        String joinNewUserList = StringUtils.join(newUserList, ",");
        String joinTotalUserList = StringUtils.join(totalUserList, ",");

        return UserReportVO.builder()
                .dateList(joinDateList)
                .newUserList(joinNewUserList)
                .totalUserList(joinTotalUserList)
                .build();
    }

    /**
     * 统计指定时间区间内的订单数据
     * @param begin 开始时间
     * @param end 结束时间
     */
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //当前集合用于存放从begin到end范围内的每天日期
        List<LocalDate> dateList=new ArrayList<>();

        dateList.add(begin);
        while (!begin.equals(end)){
            //日期计算，计算指定日期的后一天对应的日期
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        //org.apache.commons.lang3.StringUtils工具包里面方法封装对应OrderReportVO里面要求的前端数据格式
        String joinDateList = StringUtils.join(dateList, ",");

        //存放每天订单总数
        List<Long> orderCountList=new ArrayList<>();
        //存放每天有效订单数
        List<Long> validOrderCountList=new ArrayList<>();

        //遍历dateList集合，查询每天的有效订单数和订单总数
        for (LocalDate date : dateList) {
            //查询data日期对应的用户数量
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询每天订单总数
            Long orderCount = getOrderCount(beginTime, endTime, null);
            //查询每天有效订单数
            Long validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);
            //将每天订单总数添加到集合
            orderCountList.add(orderCount);
            //将每天有效订单数添加到集合
            validOrderCountList.add(validOrderCount);
        }

        String joinOrderCountList = StringUtils.join(orderCountList, ",");
        String joinValidOrderCountList = StringUtils.join(validOrderCountList, ",");

        //计算时间区间内的订单总数
        Long totalOrderCount = orderCountList.stream().reduce(Long::sum).get();
        //计算时间区间内的有效订单总数
        Long validOrderCount = validOrderCountList.stream().reduce(Long::sum).get();
        //计算订单完成率
        double orderCompletionRate =0.0;
        if (totalOrderCount != 0){
            orderCompletionRate=validOrderCount.doubleValue()/totalOrderCount;
        }

        //封装结果

        return OrderReportVO.builder()
                .dateList(joinDateList)
                .orderCountList(joinOrderCountList)
                .validOrderCountList(joinValidOrderCountList)
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 根据条件统计订单数量
     * @param begin 开始时间
     * @param end 结束时间
     * @param status 订单状态
     */
    private Long getOrderCount(LocalDateTime begin,LocalDateTime end,Integer status){

        QueryWrapper<Orders>queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda()
                .ge(begin!=null,Orders::getOrderTime,begin)
                .le(end!=null,Orders::getOrderTime,end)
                .eq(status!=null,Orders::getStatus,status);
        return orderMapper.selectCount(queryWrapper);
    }

    /**
     * 统计指定时间区间内的销售排名前10
     * @param begin 开始时间
     * @param end 结束时间
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        //转成LocalDateTime
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        //查询指定时间区间内的销售排名前10
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);

        //利用stream流来获取nameList和numberList
        List<String> nameList = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String joinNameList = StringUtils.join(nameList, ",");
        String joinNumberList = StringUtils.join(numberList, ",");

        //封装对象SalesTop10ReportVO

        //返回SalesTop10ReportVO对象
        return SalesTop10ReportVO.builder()
                .nameList(joinNameList)
                .numberList(joinNumberList)
                .build();
    }

}
